/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Product;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * Controller - 会员中心 - 商品收藏
 */
@Controller("aslMemberFavoriteController")
@RequestMapping("/weChat/favorite")
public class FavoriteController extends BaseController {

    /**
     * 每页记录数
     */
    private static final int PAGE_SIZE = 10;

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public
    @ResponseBody
    Object add(Long id) {
        Product product = productService.find(id);

        if (product == null) {
            return ERROR_MESSAGE;
        }
        Member member = memberService.getCurrent();
        if (member.getFavoriteProducts().contains(product)) {
            member.getFavoriteProducts().remove(product);
            memberService.update(member);
            return JsonMessage.error("取消收藏成功");
        }
        member.getFavoriteProducts().add(product);
        memberService.update(member);
        return JsonMessage.success("收藏成功");
    }

    /**
     * 列表
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(ModelMap model) {
        Member member = memberService.getCurrent();
        model.addAttribute("products", new ArrayList<>(member.getFavoriteProducts()));
        return "/yijing/favorite";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage delete(Long id) {
        try {
            Product product = productService.find(id);
            if (product == null) {
                return JsonMessage.error("操作错误");
            }
            Member member = memberService.getCurrent();
            if (!member.getFavoriteProducts().contains(product)) {
                return JsonMessage.error("操作错误");
            }
            member.getFavoriteProducts().remove(product);
            memberService.update(member);
            return JsonMessage.success("已取消关注");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}